package cn.zwx.member.svc.utils;


import cn.zwx.base.exception.BizWrapException;
import cn.zwx.member.svc.config.SmsConfig;
import cn.zwx.member.svc.domain.enums.MemberCodeEnum;
import cn.zwx.member.svc.domain.warp.ExceptionWrap;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author zhangwenxue
 */
@Component
public class SmsUtil {

    public static final Logger logger = LoggerFactory.getLogger(SmsUtil.class);
    @Resource
    private SmsConfig smsConfig;

    @Resource
    private Client client;

    /**
     * 发送短信
     */
    public  Boolean sendSms(String phone, String code,String templateCode) throws BizWrapException {
        SendSmsRequest request = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setTemplateCode(templateCode)
                .setTemplateParam(code)
                .setSignName(smsConfig.getSignName());
        SendSmsResponse response;
        try {
            response = client.sendSms(request);
        } catch (Exception e) {
            throw ExceptionWrap.wrap(MemberCodeEnum.SEND_MSG_ERROR);
        }
        SendSmsResponseBody body = response.getBody();
        if (response.getStatusCode() == HttpStatus.OK.value() && Objects.nonNull(response.getBody())) {
            logger.info("短信发送的回调参数为:code:{},message:{}",body.getCode(),body.getMessage());
            return "OK".equals(body.code) ? Boolean.TRUE : Boolean.FALSE;
        }
        logger.error("短信发送失败回调参数为:code:{},message:{}",body.getCode(),body.getMessage());
        return Boolean.FALSE;
    }

}
